package tree.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import tree.domain.Node;

public class TreeUtils {
	
	public static Node buildTree(List<Node> nodes){
		Node root = new Node();
		
		Map<String,Node> nodeMap = new HashMap<String,Node>();
		for(Node node:nodes){
			nodeMap.put(node.getId(), node);
		}
		
		for(Map.Entry<String, Node> nodeEntry:nodeMap.entrySet()){
			Node node = nodeEntry.getValue();
			if(node.getPid()==null||node.getPid()==""){
				root = node;
			}else{
				Node parent = nodeMap.get(node.getPid());
				if(parent!=null)
					parent.addChild(node);
			}
		}
		
		root.sortChildren();
		
		return root;
	}

}
